﻿using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.TaskApp.Dtos;
using PLCS.Client.IService.EquipmentManager;
using PLCS.Client.IService.LogManager;
using PLCS.Shared.Common.Constant;

using Prism.Commands;
using Prism.Services.Dialogs;

using Volo.Abp.ObjectMapping;

namespace PLCS.App.OrderTask.ViewModels.TaskModule;

internal class TaskDetailViewModel : HostDialogViewModel
{
    public TaskDetailViewModel(IObjectMapper<OrderTaskModule> objectMapper, ITaskService taskService, IEquipmentService equipmentService)
    {
        _objectMapper = objectMapper;
        _taskService = taskService;
        _equipmentService = equipmentService;
        View = "任务管理弹窗";
    }

    private TaskDto _model;
    private readonly IObjectMapper<OrderTaskModule> _objectMapper;
    private readonly ITaskService _taskService;
    private readonly IEquipmentService _equipmentService;

    public TaskDto Model
    {
        get { return _model; }
        set { SetProperty(ref _model, value); }
    }

    private ObservableCollection<string> _equipmentList;

    public ObservableCollection<string> EquipmentList
    {
        get { return _equipmentList; }
        set { SetProperty(ref _equipmentList, value); }
    }

    public DelegateCommand DropOpenedCommand => new DelegateCommand(DropOpened);

    private async void DropOpened()
    {
        var equipments = await _equipmentService.GetListAsync();
        EquipmentList = equipments.Select(x => x.EquNum).ToObservable();
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var task = _objectMapper.Map<TaskDto, TaskEditDto>(Model);
            if (task.Id != Guid.Empty)
            {
                await _taskService.UpdateAsync(task);
                Log("修改", task);
            }
            else
            {
                await _taskService.CreateAsync(task);
                Log("新增", task);
            }
            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally
        {
            SavebuttonIsEnabled = true;
        }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<TaskDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new TaskDto();
        }
    }
}